/**
 * Copyright (c) 2006 Amgad S Youssef
 * All Rights Reserved.
 * Licensed under the Eclipse Public License - v 1.0
 * For more information see http://www.eclipse.org/legal/epl-v10.html
 */
package org.eclipsejcde.preferences.pages;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.preference.DirectoryFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipsejcde.core.Activator;
import org.eclipsejcde.core.JCDECore;
import org.eclipsejcde.core.preferences.JCPreferenceConstants;

/**
 * @author Amgad S Youssef
 * 
 */
public class JCHomeLocationPage extends FieldEditorPreferencePage implements
		IWorkbenchPreferencePage {

	private DirectoryFieldEditor jcdkHome;

	// private DirectoryFieldEditor jdkHome;

	public JCHomeLocationPage() {
		super(GRID);
		setPreferenceStore(Activator.getDefault().getPreferenceStore());
		setDescription("Set home location for the Java Card Development Kit and Java Home");
	}

	@Override
	public void createFieldEditors() {
		jcdkHome = new DirectoryFieldEditor(
				JCPreferenceConstants.JAVA_CARD_PATH, "&Java Card Home:",
				getFieldEditorParent());
		addField(jcdkHome);
	}

	@Override
	public void init(IWorkbench workbench) {
	}

	@Override
	public boolean performOk() {
		String javacardHome = jcdkHome.getStringValue();
		if (validateJCDKHome(javacardHome)) {
			return super.performOk();
		} else {
			return false;
		}
	}

	private boolean validateJCDKHome(String jcdkHome) {
		setErrorMessage(null);
		setMessage(null, IMessageProvider.WARNING);

		// validate JCDK home
		IStatus status = JCDECore.validateJCDKHomeCompatibility(jcdkHome);
		if (status.getSeverity() == IStatus.ERROR) {
			setErrorMessage(status.getMessage());
			return false;
		} else if (status.getSeverity() == IStatus.WARNING) {
			setMessage(status.getMessage(), IMessageProvider.WARNING);
		}

		return true;
	}
}